package com.hotelsystem.reservations.reservations;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

import com.google.gson.Gson;

/**
 * Class providing logic implemented by number of 
 * threads for move reservations from future to current
 * 
 * @author Peter Lazarov
 *
 */
public class ReservationsWorker extends Thread {
	
	protected File[] files;
	protected String sourceDirectory;
	protected String destinationDirectory;

	public ReservationsWorker(File[] files, String sourceDirectory, String destinationDirectory) {
		super();
		this.sourceDirectory = sourceDirectory;
		this.destinationDirectory = destinationDirectory;
		this.files = files;
	}
	
	public void run() {
		findFilesToMove();
	}
	/**
	 * THIS METOD MUST BE OVERRIDDEN!
	 * It should call the function that moves all reservations from source directory in destination directory  
	 */
	protected void findFilesToMove() {

	}

	/**
	 * Moves file from source directory to destination directory
	 * @param file - file to be moved
	 */
	public void moveFile(File file) {
		File sourcePath = new File (sourceDirectory + file.getName());
		File destinationPath = new File (destinationDirectory + file.getName());
		
		try {
			Files.move(sourcePath.toPath(), destinationPath.toPath(), StandardCopyOption.REPLACE_EXISTING);
		} catch (IOException e) {
			System.out.println("IO Exception on moving reservation from future to current!");
			e.printStackTrace();
		}
	}
	
	/**
	 * Reads reservation, stored in file as json object, and convert data to POJO
	 * @param fileName - path to the file
	 * @return - reservation from the file with the given file path
	 * @throws IOException
	 */
	public Reservation readReservation(String fileName) {
		Reservation reservation = new Reservation();
		String path = sourceDirectory;
		
		Gson gson = new Gson();				    
		String jsn;
		try {
			jsn = new String(Files.readAllBytes(Paths.get(path + fileName)));
			reservation = gson.fromJson(jsn, reservation.getClass());
		} catch (IOException e) {
			System.out.println("IO Exception on reading reservation from file in future folder!");
			e.printStackTrace();
		}
	    	
	    return reservation;
	}

}